package com.example.imgservice.controller;


import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.imgservice.config.MyContent;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class uploadImg {
    @PostMapping("/upload")
    public Map<String,String> upload(MultipartFile[] files,String name) throws IOException {
        Map<String,String> map=new HashMap<>();
        System.out.println(Arrays.toString(files));
        if(files.length==0){
            map.put("code","200");
            map.put("reason","您上传的照片为空");
            return map;
        }
        //获取当前目录所在位置
        String rootA= MyContent.PRO_PATH;
        //指定文件
        File all = new File(rootA, "myCollect");
        if(!all.exists()){
            System.out.println(all.mkdirs());
        }
        String root=rootA+File.separator+"myCollect";
        //获取当前时间戳
        long time = new Date().getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(time);
        //创建文件夹
        File img = new File(root, format1);
        if(!img.exists()){
            System.out.println(img.mkdirs());
        }
        if(files.length==1){
            //修改图片名称
            String s = Objects.requireNonNull(files[0].getOriginalFilename()).split("\\.")[1];
            String newFilename=name+"."+s;
            files[0].transferTo(new File(root+File.separator+format1,newFilename));
        }else {
            //创建文件夹存入图片
            String newFileRoot=root+File.separator+format1;
            File imgName = new File(newFileRoot, name);
            if(!imgName.exists()){
                System.out.println(imgName.mkdirs());
            }
            for (MultipartFile file : files) {
                //获取当前时间戳
                String filename = file.getOriginalFilename();
                long times = new Date().getTime();
                String replace= UUID.randomUUID().toString().replace("-","");
                assert filename != null;
                //利用UUID改名
                String newFilename = times + "-" + replace + filename.substring(filename.lastIndexOf("."));
                file.transferTo(new File(root+File.separator+format1+File.separator+name, newFilename));
            }
        }
        map.put("code","200");
        map.put("reason","上传成功");
        map.put("path",root);
        return map;
    }
}
